package com.java.basis.thread;


import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TestThreadState")
public class TestThreadState {

//    private static final Logger logger = LoggerFactory.getLogger(TestThreadState.class);
    static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException {
//        testNewRunnableTerminated();
        testBlocked();
//        testWaiting();

    }
    //数字表示要按照顺序进行测试
    private static void testNewRunnableTerminated() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.info("running...");// 3
        }, "t1");
        log.info("state: {}", t1.getState());// 1
        t1.start();
        log.info("state: {}", t1.getState());// 2
        t1.join();
        log.info("state: {}", t1.getState());// 4

    }

    private static void testWaiting() {
        Thread t2 = new Thread(() -> {
            synchronized (LOCK) {
                log.debug("before waiting");// 1
                try {
                    LOCK.wait(); // 3
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "t2");
        t2.start();
        log.debug("state: {}", t2.getState());// 2
        synchronized (LOCK) {
            log.debug("state: {}", t2.getState());// 4
            LOCK.notify(); // 5
            log.debug("state: {}", t2.getState());// 6
        }

        log.debug("state: {}", t2.getState());// 7


    }

    private static void testBlocked() throws InterruptedException {
        Thread t2 = new Thread(() -> {
            log.debug("before sync");// 3
            synchronized (LOCK) {
                log.debug("in sync");// 4
            }
        }, "t2");
        t2.start();
        log.debug("state: {}", t2.getState());// 1
        synchronized (LOCK) {
            log.debug("state: {}", t2.getState());// 2
        }
        log.debug("state: {}", t2.getState());// 5

    }

}
